package com.starbaba.module.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.common.ResultJson;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.utils.JSONUtils;
import com.starbaba.module.model.ApiModelItem;
import com.starbaba.module.model.ApiModelItemArray;
import com.starbaba.module.model.LoanApiActivity;
import com.starbaba.module.model.LoanApiModel;
import com.starbaba.module.service.ApiActivityService;
import com.starbaba.tools.sequence.Sequence;

@SuppressWarnings("rawtypes")
public class APIActivityAction extends BaseAction implements ModelDriven {
	
	private static final long serialVersionUID = 1L;
	
	private BaseDao dao = new BaseDao(Constant.POOL_LIFE);

	
	@Resource(name="apiActivityServiceImpl")
	private ApiActivityService apiActivityService;
	
	public String show(){
		return "success";
	}
	
	public String addPage(){
		String sql = "SELECT * FROM loan_api_model mo";
		try {
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			List<LoanApiModel> modelList = dao.list(sql, LoanApiModel.class);
			paramsMap.put("modelList", modelList);
			String id = (String) paramsMap.get("id");
			if(id != null && !"".equals(id)){
				String selectSql = "SELECT * FROM loan_api_activity ac WHERE ac.id = ?";
				LoanApiActivity activity = dao.get(selectSql, LoanApiActivity.class, id);
				paramsMap.put("activity", activity);
			}
		} catch (AppException e) {
			e.printStackTrace();
		}
		return "success";
	}
	
	public void savedActivity(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String activityName = (String) paramsMap.get("name");
    	String remark = (String) paramsMap.get("memo");
    	Long modelId = Long.valueOf((String) paramsMap.get("mid"));
    	Long activityId = Sequence.getSequence();
    	LoanApiActivity model = new LoanApiActivity();
    	model.setActivity_name(activityName);
    	model.setRemark(remark);
    	model.setApi_module_id(modelId);
    	model.setCtime(new Date());
    	model.setUptime(new Date());
		try {
			if(id == null || "".equals(id)){
				apiActivityService.saveActivity(model);
			}else{
				model.setId(Long.valueOf(id));
				apiActivityService.updateActivity(model);
			}
			
        } catch (AppException e1) {
            responseError(e1);
            e1.printStackTrace();
        }
        responseSuccess();
	}
	
	public void querylist(){ 
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		List list = apiActivityService.getDataList(start, length, pageResponse, paramsMap);
		pageResponse.setAaData(list);
		pageResponse.setSEcho(pageRequest.getSEcho());
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			LogService.error(e);
		}
	}
	
	public void updateContext(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		try {
			apiActivityService.updateContext(paramsMap);
			responseSuccess();
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
	}
	
	public void selectActivity(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String activityId = (String)paramsMap.get("activityId");
		String modelId = (String)paramsMap.get("modelId");
		String modelSql = "SELECT * FROM loan_api_model mo WHERE mo.id = ?";
		String activitySql = "SELECT * FROM loan_api_activity ac WHERE ac.id = ?";
		try {
			LoanApiModel model = dao.get(modelSql,LoanApiModel.class, modelId);
			List<ApiModelItem> modelItemList = JSONUtils.fromJsonArray(model.getProperties(),ApiModelItem.class);
			LoanApiActivity activity = dao.get(activitySql,LoanApiActivity.class, activityId);
			if(activity.getProp_item() != null && !"".equals(activity.getProp_item())){
				System.out.println();
			}else{
				try {
					sendJsonMessage(JsonUtils.toJson(modelItemList, null, true, null, false));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (AppException e) {
			e.printStackTrace();
		}
		
	}
	
	
	
	
	/**
     * 
     *
     * @Title responseSuccess
     * @Description <p>
     *              返回错误信息
     *              </p>
     *              　　　　　
     * @author zhengjunjie
     * @dateTime 2015年10月16日 下午2:26:53
     *
     */
    private void responseError(Exception error) {
        StringWriter writer = new StringWriter();
        error.printStackTrace(new PrintWriter(writer, true));
        ResultJson resultJson = new ResultJson(-2, 0, writer.toString());
        JsonObject result = new JsonObject();
        result.add("result", resultJson.toJSON());
        try {
            sendJsonMessage(result.toString());
        } catch (Exception e) {
            LogService.error(e);
        }
    }
    
    private void responseSuccess() {
        JsonObject result = new JsonObject();
        result.add("result", new ResultJson().toJSON());
        try {
            sendJsonMessage(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	@Override
	public LoanApiActivity getModel() {
		return null;
	}

    
}
